const Service = require('egg').Service;

class SmsService extends Service {


	async send(para) {

		let { mobile, info, signName, templateCode } = para;

		signName = signName || '香草科技';
        templateCode = templateCode || 'SMS_153992037';

        // console.log('service send');
        // console.log(mobile);
        // console.log(info);
        // console.log(signName);
        // console.log(templateCode);
        // console.log(JSON.stringify(info));

		const rr = await new Promise((resolve, reject) => {

			this.app.smsClient.sendSMS({
	            PhoneNumbers: mobile,//必填:待发送手机号。支持以逗号分隔的形式进行批量调用，批量上限为1000个手机号码,批量调用相对于单条调用及时性稍有延迟,验证码类型的短信推荐使用单条调用的方式；发送国际/港澳台消息时，接收号码格式为：国际区号+号码，如“85200000000”
	            SignName: signName,//必填:短信签名-可在短信控制台中找到
	            TemplateCode: templateCode,//必填:短信模板-可在短信控制台中找到，发送国际/港澳台消息时，请使用国际/港澳台短信模版
	            TemplateParam: JSON.stringify(info) //可选:模板中的变量替换JSON串,如模板内容为"亲爱的${name},您的验证码为${code}"时。
	        }).then(function (res) {
	        	console.log('111');
	        	console.log(res);
	        	resolve(res);

	        }, function (res) {
	        	console.log('222');
	        	console.log(res);
	            reject(res);
	        })
		});

		console.log(rr);

		return rr;
	}


	async savelog (para) {

		let { mobile, content, requestid, code, message, bizid, order_code, state, failmsg } = para;

		const sql = this.app.mysql.get('weshop');

		let result = {};

		try{
			result = await sql.query(
				'insert into smslog ' +
				'(mobile, content, requestid, code, message, bizid, order_code, create_time, state, failmsg) ' + 
				'VALUES ' + 
				'(?, ?, ?, ?, ?, ?, ?, NOW(), ?, ?)', [mobile, content, requestid, code, message, bizid, order_code, state, failmsg]
			);
		}catch (err){
			this.app.logger.info(err);
		}

		//console.log(result);

		return result.affectedRows === 1;

	}


	async info (order_code) {
		const sql = this.app.mysql.get('weshop');
		const result = await sql.query(
			'select mobile , content, requestid, code, message, bizid, CAST(create_time AS CHAR) as create_time, state, failmsg '+
			'from smslog where order_code=? order by create_time desc', [order_code]
		);
		return result;
	}

  	
}

module.exports = SmsService;

